package xyz.naokeziteng.data_structure.graph_theory;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author hawk
 * @date 2022/10/8
 * @desc 广度优先遍历单源路径
 **/
public class BfsSingleSourcePath {

    private Graph G;
    private boolean[] visited;
    //上一个节点
    private int[] pre;
    //原点
    private int s;


    public BfsSingleSourcePath(Graph G, int s) {
        G.validateVertex(s);
        this.G = G;
        this.s = s;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        Arrays.fill(pre, -1);
        bfs(s);
    }

    //广度优先遍历
    private void bfs(int s) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(s);
        visited[s] = true;
        while (!queue.isEmpty()) {
            int v = queue.poll();
            for (int w : G.adj(v)) {
                if (!visited[w]) {
                    pre[w] = v;
                    queue.offer(w);
                    visited[w] = true;
                }
            }
        }
    }

    public boolean isConnected(int t) {
        G.validateVertex(t);
        return visited[t];
    }

    //寻找单源路径
    public String path(int v) {
        G.validateVertex(v);
        if (!isConnected(v)) {
            return "没有路径...";
        }
        StringBuilder sb = new StringBuilder();
        int p = v;
        while (p != s) {
            sb.append(p).append("<--");
            p = pre[p];
        }
        return sb.append(p).toString();
    }


    public static void main(String[] args) {
        BfsSingleSourcePath bfs = new BfsSingleSourcePath(new Graph("src/main/resources/g.txt"), 0);
        System.out.println(bfs.path(6));
        System.out.println(bfs.path(4));
    }
}
